package cn.javase.base.multithread._06_线程安全问题;

public class _卖票 {

    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        MyThread t3 = new MyThread();
        MyThread t4 = new MyThread();
        MyThread t5 = new MyThread();
        MyThread t6 = new MyThread();
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
        t6.start();
    }

    private static class MyThread extends Thread {
        public static int ticket = 0;   // 票数
        @Override
        public void run() {
            while (true) {
                synchronized (MyThread.class) {
                    if (ticket < 100) {
                        // 中间睡的时间长一点就会产生线程安全问题
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                        ticket++;
                        System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "张票");
                    } else {
                        break;
                    }
                }
            }
        }
    }

}
